<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类ID" prop="categoryId">
        <el-tree-select v-model="queryParams.categoryId" :data="categoryOptions"
          :props="{ value: 'categoryId', label: 'name', children: 'children' }" value-key="categoryId"
          placeholder="请选择分类" check-strictly />
        <!-- <el-input v-model="queryParams.categoryId" placeholder="请输入分类ID" clearable @keyup.enter="handleQuery" /> -->
      </el-form-item>
      <el-form-item label="资源标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入资源标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="资源标识" prop="slug">
        <el-input v-model="queryParams.slug" placeholder="请输入资源标识" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="发布用户ID" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入发布用户ID" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="浏览次数" prop="viewCount">
        <el-input v-model="queryParams.viewCount" placeholder="请输入浏览次数" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="下载次数" prop="downloadCount">
        <el-input v-model="queryParams.downloadCount" placeholder="请输入下载次数" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resourceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="80" />
      <el-table-column label="资源标题" align="center" prop="title" />
      <el-table-column label="封面图URL" align="center" prop="cover" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.cover" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="发布用户ID" align="center" prop="userId" />
      <el-table-column label="浏览次数" align="center" prop="viewCount">
        <template #default="scope">
          <el-tag>{{ scope.row.viewCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下载次数" align="center" prop="downloadCount">
        <template #default="scope">
          <el-tag type="success">{{ scope.row.downloadCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" align="center" prop="isRecommend">
        <template #default="scope">
          <el-switch v-model="scope.row.isRecommend" active-value="1" inactive-value="0"
            @click="isRecommendChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
            @click="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 查看详情对话框 -->
    <el-dialog title="查看详情" v-model="openDetail" width="1000px" inline="true">
      <el-form :model="detailForm" label-width="100px">
        <el-form-item label="资源标题" prop="title">
          <el-input v-model="detailForm.title" disabled />
        </el-form-item>
        <el-form-item label="父分类" prop="categoryName">
          <el-input v-model="detailForm.categoryName" disabled />
        </el-form-item>

        <el-form-item label="资源标识" prop="slug">
          <el-input v-model="detailForm.slug" disabled />
        </el-form-item>
        <el-form-item label="封面图URL" prop="cover">
          <image-preview :src="detailForm.cover" :width="50" :height="50" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="平台" prop="userId">
              <el-tag type="success" effect="light" round>{{ detailForm.resourceLink.platform }}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提取码" prop="userId">
              <el-tag type="success" effect="light" round>{{ detailForm.resourceLink.password }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="发布用户ID" prop="userId">
          <el-input v-model="detailForm.userId" disabled />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="浏览次数" prop="viewCount">
              <el-tag type="success">{{ detailForm.viewCount }}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下载次数" prop="downloadCount">
              <el-tag type="warning">{{ detailForm.downloadCount }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="资源描述" prop="description">
          <el-input v-model="detailForm.description" type="textarea" disabled />
        </el-form-item>
        <el-form-item label="详细介绍">
          <el-input v-model="detailForm.content" type="textarea" disabled />

        </el-form-item>
        <el-form-item label="发布用户ID" prop="userId">
          <el-input v-model="detailForm.userId" disabled />
        </el-form-item>
        <el-form-item label="标签" prop="userId">
          <el-tag type="success" effect="light" round v-for="item in detailForm.tags">{{ item }}</el-tag>
        </el-form-item>
        <el-form-item label="链接" prop="userId">
          <el-input v-model="detailForm.resourceLink.linkUrl" disabled />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancelDetail">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改资源对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="resourceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资源标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入资源标题" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-tree-select v-model="form.categoryId" :data="categoryOptions"
            :props="{ value: 'categoryId', label: 'name', children: 'children' }" value-key="categoryId"
            placeholder="请选择分类" check-strictly />
        </el-form-item>
        <el-form-item label="资源标识" prop="slug">
          <el-input v-model="form.slug" placeholder="请输入资源标识" />
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <image-upload v-model="form.cover" />
        </el-form-item>
        <el-form-item label="资源描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="详细介绍">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="浏览次数" prop="viewCount">
          <el-slider v-model="form.viewCount" show-input :max=99999 />
        </el-form-item>
        <el-form-item label="下载次数" prop="downloadCount">
          <el-slider v-model="form.downloadCount" show-input :max=99999 />
        </el-form-item>
        <el-form-item label="分享链接" prop="linkUrl">
          <el-input v-model="form.resourceLink.linkUrl" placeholder="请输入分享链接" />
        </el-form-item>
        <el-form-item label="分享码" prop="resourceLink">
          <el-input v-model="form.resourceLink.password" placeholder="请输入提取码" />
        </el-form-item>
        <el-form-item label="平台类型" prop="resourceLink">
          <el-input v-model="form.resourceLink.platform" placeholder="请输入平台类型" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-checkbox-group v-model="form.tags" :min="1" :max="5">
            <el-checkbox v-for="tag in tagsList" :key="tag.tagId" :label="tag.tagId" :value="tag.tagId">
              {{ tag.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Resource">
import { listResource, getResource, delResource, addResource, updateResource } from "@/api/share/resource"
import { listCategory } from "@/api/share/category"
import { listTag } from "@/api/share/tag"
import { loadAllParams } from "@/api/page"


const { proxy } = getCurrentInstance()

const resourceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const openDetail = ref(false)
const data = reactive({
  form: {},
  detailForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    title: null,
    slug: null,
    cover: null,
    description: null,
    content: null,
    userId: null,
    viewCount: null,
    downloadCount: null,
    isRecommend: null,
    status: null
  },
  rules: {
    categoryId: [
      { required: true, message: "分类ID不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "资源标题不能为空", trigger: "blur" }
    ],
    //  linkUrl: [
    //   { required: true, message: "资源链接不能为空", trigger: "blur" }
    // ],
  }
})

const { queryParams, form, rules, detailForm } = toRefs(data)

/** 查询资源列表 */
function getList() {
  loading.value = true
  listResource(queryParams.value).then(response => {
    console.log(response);
    resourceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}
// 取消详情按钮
function cancelDetail() {
  openDetail.value = false
}
// 表单重置
function reset() {
  form.value = {
    resourceId: null,
    categoryId: null,
    title: null,
    slug: null,
    cover: null,
    description: null,
    content: null,
    userId: null,
    viewCount: null,
    downloadCount: null,
    isRecommend: null,
    status: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    tags: [],
    resourceLink: {
      linkUrl: null,
      password: null,
      platform: null
    }
  }
  proxy.resetForm("resourceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.resourceId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getTreeselect()
  open.value = true
  title.value = "添加资源"
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  await getTreeselect()
  const _resourceId = row.resourceId || ids.value
  getResource(_resourceId).then(response => {
    form.value = response.data 
    open.value = true
    title.value = "修改资源"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["resourceRef"].validate(valid => {
    if (valid) {
      if (form.value.resourceId != null) {
        updateResource(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addResource(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _resourceIds = row.resourceId || ids.value
  proxy.$modal.confirm('是否确认删除资源编号为"' + _resourceIds + '"的数据项？').then(function() {
    return delResource(_resourceIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
/** 查看详情  */
function handleDetail(row) {
  getResource(row.resourceId).then(response => {
    detailForm.value = response.data
    openDetail.value = true
    detailForm.value.categoryName = bornCategoryOptions.value.filter(item => item.categoryId === response.data.categoryId)[0].name
      detailForm.value.tags = tagsList.value
      .filter(tag => response.data.tags.some(resourceTag => resourceTag === tag.tagId))
      .map(tag => tag.name)
  })
  
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('share/resource/export', {
    ...queryParams.value
  }, `resource_${new Date().getTime()}.xlsx`)
}
/** 修改状态 */
const handleStatusChange = (row) => {
    updateResource({
      resourceId: row.resourceId,
      status: row.status == 0 ? 0 : 1
    }).then(() => {
      proxy.$modal.msgSuccess("修改成功")
    })
}
/** 修改是否推荐 */
const isRecommendChange = (row) => {
    updateResource({
      resourceId: row.resourceId,
      isRecommend: row.isRecommend == 0 ? 0 : 1
    }).then(() => {
      proxy.$modal.msgSuccess("修改成功")
    })
}
const categoryOptions = ref([])
const bornCategoryOptions = ref([])
/** 查询资源分类下拉树结构 */
function getTreeselect() {
  listCategory().then(response => {
    bornCategoryOptions.value = response.data
    categoryOptions.value = []
    const data = { categoryId: 0, name: '顶级节点', children: [] }
    data.children = proxy.handleTree(response.data, "categoryId", "parentId")
    console.log(data);
    categoryOptions.value.push(data)
  })
}
const tagsList = ref([])
/** 查询标签列表 */
function getTagList() {
  listTag(loadAllParams).then(response => {
    console.log("tag",response);
    tagsList.value = response.rows
  })
}
getTagList()
getTreeselect()
getList()
</script>
